#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速测试脚本 - 简单验证算法服务是否正常工作
"""

import requests
import json
import time

def test_audit_service(base_url="http://localhost:8001"):
    """快速测试审核服务"""
    
    print("🚀 开始快速测试内容审核服务...")
    print(f"📡 服务地址: {base_url}")
    print("-" * 50)
    
    # 1. 健康检查
    print("1️⃣ 健康检查...")
    try:
        response = requests.get(f"{base_url}/health", timeout=5)
        if response.status_code == 200:
            print("✅ 服务运行正常")
        else:
            print(f"❌ 服务异常: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 连接失败: {e}")
        return False
    
    # 2. 测试正常内容
    print("\n2️⃣ 测试正常内容...")
    normal_data = {
        "post_id": "test_normal",
        "content": "今天天气真好，适合出去散步，分享一些生活感悟",
        "title": "美好的一天",
        "author_id": 999,
        "images": [],
        "timestamp": time.time()
    }
    
    try:
        response = requests.post(f"{base_url}/audit", json=normal_data, timeout=10)
        if response.status_code == 200:
            result = response.json()
            print(f"✅ 审核结果: {result.get('audit_result')}")
            print(f"📊 置信度: {result.get('confidence', 0):.3f}")
        else:
            print(f"❌ 请求失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 测试异常: {e}")
    
    # 3. 测试违规内容
    print("\n3️⃣ 测试违规内容...")
    violation_data = {
        "post_id": "test_violation",
        "content": "杀人放火抢劫银行，免费领取iPhone，加微信获取更多信息",
        "title": "震惊！你绝对想不到的秘密",
        "author_id": 999,
        "images": [],
        "timestamp": time.time()
    }
    
    try:
        response = requests.post(f"{base_url}/audit", json=violation_data, timeout=10)
        if response.status_code == 200:
            result = response.json()
            print(f"✅ 审核结果: {result.get('audit_result')}")
            print(f"📊 置信度: {result.get('confidence', 0):.3f}")
            print(f"⚠️ 违规原因: {result.get('reasons', [])}")
        else:
            print(f"❌ 请求失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 测试异常: {e}")
    
    # 4. 测试图片审核
    print("\n4️⃣ 测试图片审核...")
    image_data = {
        "post_id": "test_image",
        "content": "分享一张图片",
        "title": "图片分享",
        "author_id": 999,
        "images": ["https://codefather.cn/logo.png"],
        "timestamp": time.time()
    }
    
    try:
        response = requests.post(f"{base_url}/audit", json=image_data, timeout=15)
        if response.status_code == 200:
            result = response.json()
            print(f"✅ 审核结果: {result.get('audit_result')}")
            print(f"📊 置信度: {result.get('confidence', 0):.3f}")
            
            # 显示图片审核详情
            details = result.get('details', {})
            image_audit = details.get('image_audit', [])
            if image_audit:
                for i, img_result in enumerate(image_audit):
                    print(f"🖼️ 图片{i+1}: {'安全' if img_result.get('is_safe') else '不安全'}")
        else:
            print(f"❌ 请求失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 测试异常: {e}")
    
    # 5. 性能测试
    print("\n5️⃣ 性能测试...")
    start_time = time.time()
    
    try:
        perf_data = {
            "post_id": "test_performance",
            "content": "这是一个性能测试的内容，用于测试处理速度和响应时间",
            "title": "性能测试",
            "author_id": 999,
            "images": [],
            "timestamp": time.time()
        }
        
        response = requests.post(f"{base_url}/audit", json=perf_data, timeout=10)
        end_time = time.time()
        
        if response.status_code == 200:
            processing_time = end_time - start_time
            print(f"✅ 处理时间: {processing_time:.3f}秒")
            
            if processing_time < 1.0:
                print("🚀 性能优秀")
            elif processing_time < 3.0:
                print("👍 性能良好")
            else:
                print("⚠️ 性能需要优化")
        else:
            print(f"❌ 性能测试失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 性能测试异常: {e}")
    
    print("\n" + "=" * 50)
    print("🎉 快速测试完成！")
    print("💡 如需详细测试，请运行: python test_audit_system.py")
    
    return True


def test_api_endpoints(base_url="http://localhost:8001"):
    """测试API端点"""
    print("\n🔍 测试API端点...")
    
    endpoints = [
        ("/", "GET", "根路径"),
        ("/health", "GET", "健康检查"),
        ("/docs", "GET", "API文档"),
        ("/metrics", "GET", "监控指标")
    ]
    
    for endpoint, method, description in endpoints:
        try:
            if method == "GET":
                response = requests.get(f"{base_url}{endpoint}", timeout=5)
            
            status = "✅" if response.status_code == 200 else "❌"
            print(f"{status} {endpoint} ({description}): {response.status_code}")
            
        except Exception as e:
            print(f"❌ {endpoint} ({description}): 连接失败")


if __name__ == "__main__":
    import sys
    
    # 获取服务地址
    if len(sys.argv) > 1:
        service_url = sys.argv[1]
    else:
        service_url = "http://localhost:8001"
    
    print("🧪 内容审核服务快速测试工具")
    print("=" * 50)
    
    # 运行测试
    success = test_audit_service(service_url)
    
    # 测试API端点
    test_api_endpoints(service_url)
    
    if success:
        print("\n✅ 所有测试通过！服务运行正常")
        sys.exit(0)
    else:
        print("\n❌ 测试失败！请检查服务状态")
        sys.exit(1)
